#include "animationwindow.h"

#include <QPainter>
#include <QTimer>

AnimationWindow::AnimationWindow(QWidget *parent) : QWidget(parent)
{

}

void AnimationWindow::showBetScore(int bet)
{
    m_x = 0;
    if(bet == 1)
    {
        m_image.load(":/images/score1.png");
    }
    else if(bet == 2)
    {
        m_image.load(":/images/score2.png");
    }
    else if(bet == 3)
    {
        m_image.load(":/images/score3.png");
    }
    update();  //刷新 会调用paintEvent事件

    //抢地主完成之后，将分数
    QTimer::singleShot(2000, this, &AnimationWindow::hide);
}

void AnimationWindow::showSequence(Type type)
{
    m_x = 0;
    QString name = type == Pair ? ":/images/liandui.png" : ":/images/shunzi.png";
    m_image.load(name);
    update(); //就会把m_image里面的图片，画到当前的窗口里
    QTimer::singleShot(2000, this, &AnimationWindow::hide); //2s后，当前窗口隐藏
}

void AnimationWindow::showJokerBomb()
{
    m_index = 0;
    m_x = 0;
    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [=](){
        m_index++; //每60ms加一下
        if(m_index > 8) //只有8炸张动画图片
        {
            timer->stop();
            timer->deleteLater();
            m_index = 8;
            hide();
        }
        QString name = QString(":/images/joker_bomb_%1.png").arg(m_index);
        m_image.load(name);
        update();
    });
    timer->start(60); //定时器启动之后，每隔60ms发送一个timeout
}

void AnimationWindow::showBomb()
{
    m_index = 0;
    m_x = 0;
    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [=](){
        m_index++;
        if(m_index > 12)
        {
            timer->stop();
            timer->deleteLater();
            m_index = 12;
            hide();
        }
        QString name = QString(":/images/bomb_%1.png").arg(m_index);
        m_image.load(name);
        update();
    });
    timer->start(60);
}

void AnimationWindow::showPlane()
{
    m_x = width();  //记录飞机当前的位置
    m_image.load(":/images/plane_1.png");
    setFixedHeight(m_image.height()); //设置窗口高度
    update(); //实时更新飞机位置

    int step = width() / 5; //把当前窗口分为5份，step是每一份的宽度
    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [=]()
    {
        static int dist = 0;
        static int timers = 0;
        dist += 5;
        if(dist >= step) //飞机从一个区域进入到另一个区域
        {
            dist = 0;
            timers++;
            QString name = QString(":/images/plane_%1.png").arg(timers % 5 + 1);
            m_image.load(name); //加载图片
        }
        if(m_x <= -110) //说明飞机已经飞出左边界110个像素
        {
            timer->stop();
            timer->deleteLater();
            dist = timers = 0;
            hide(); //隐藏窗口
        }
        m_x -= 5; //每触发一次定时器，坐标向左移动5个像素
        update();
    });
    timer->start(15); //启动定时器
}

void AnimationWindow::paintEvent(QPaintEvent *ev)
{
    Q_UNUSED(ev)
    QPainter p(this); //把图片画到当前窗口
    p.drawPixmap(m_x, 0, m_image.width(), m_image.height(), m_image);
}
